package com.wm.wmcrm.sys.service.impl;

import com.wm.wmcrm.sys.entity.SysRole;
import com.wm.wmcrm.sys.entity.SysUser;
import com.wm.wmcrm.sys.service.ISysRoleService;
import com.wm.wmcrm.sys.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.metadata.GenericTableMetaDataProvider;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 认证校验的方法
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    ISysUserService sysUserService;

    @Autowired
    ISysRoleService sysRoleService;

    /**
     * 完成账号的校验
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.queryByUserName(username);
        List<SysRole> sysRoles = sysRoleService.queryByUserId(sysUser.getUserId());
        if(username.equals(sysUser.getUsername())){
            List<GrantedAuthority> list = new ArrayList<>();
            sysRoles.forEach(sysRole -> {
                list.add(new SimpleGrantedAuthority(sysRole.getRoleName()));
            });
            UserDetails userDetails = new User(username,sysUser.getPassword(),list);
            return userDetails;
        }
//        if("admin".equals(username)){
//            List<GrantedAuthority> list = new ArrayList<>();
//            list.add(new SimpleGrantedAuthority("ADMIN"));
//            UserDetails userDetails = new User("admin","$2a$10$m9j79FObaqq681Moo835guFLgYEkl5Vaeow9006V6aDOiddpaus06",list);
//            return userDetails;
//        }
        return null;
    }
}
